<script lang="tsx">
import { defineComponent, ref, computed, watch, onMounted, h, nextTick } from 'vue';
import { $t } from '@vben/locales';
import BaseDrawer from '#/components/common/base-drawer.vue';
import { tenantTypeOptions } from '#/types/const';
import MenuPermissionTree from '#/components/common/menu-permission-tree.vue';
import { getSysMenuTreeApi } from '#/api/system/menuMgr';
import { createMergedObject } from '#/utils/objectMerge';
import { Ban, Pencil, SquarePlay } from '@vben/icons';
import { useCodeBox } from '#/hooks/useCodeBox';
import { verifyPhoneCodeApi } from '#/api/core/auth';
import ImageUpload from '#/components/common/image-upload.vue';


export default defineComponent({
  name: 'TenantForm',
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
    mode: {
      type: String,
      default: 'add', // add | edit
    },
  },
  emits: ['update:modelValue', 'confirm', 'cancel'],
  setup(props, { emit }) {
    const formRef = ref();
    const menuTreeRef = ref();
    const imageUploadRef = ref();
    const visible = ref(false);
    const loading = ref(false);
    const menuList = ref([]);
    const initFormData = () => {
      return {
        name: '',
        shortName: '',
        userCount: null,
        type: '',
        contact: '',
        contactPhone: '',
        contactEmail: '',
        domain: '',
        activeTime: null,
        menus: [] as number[],
        tenantLogo: undefined
      }
    }
    // 表单数据
    const localFormData = ref(initFormData() as Record<string, any>);
    const { showCodeBox, authCode } = useCodeBox();
    const getMenuList = (tenantId: string) => {
      let params: { curPage: number, pageSize: number, type?: string } = {
        curPage: 1,
        pageSize: 10000,
        // type: 'tenantManager'
      }
      if (tenantId !== '-1') {
        params['type'] = 'tenantManager'
      }
      getSysMenuTreeApi(params).then((res) => {
        menuList.value = res.data;
      });
    }

    const contactPhoneItem = ref({
      prop: 'contactPhone',
      label: $t('system.organization.phone'),
      type: 'input',
      placeholder: $t('common.inputPhTxt', [$t('system.organization.phone')]),
      required: true,
    } as Record<string, any>);
    // 基本信息表单配置
    const basicFormColumns = [
      {
        prop: 'name',
        label: $t('system.organization.tenantName'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('system.organization.tenantName')]),
        required: true,
        maxlength: 50
      },
      {
        prop: 'shortName',
        label: $t('system.organization.shortName'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('system.organization.shortName')]),
        required: true,
        maxlength: 50
      },
      {
        prop: 'userCount',
        label: $t('system.organization.userCount'),
        componentName: 'el-input',
        type: 'number',
        step: '1',
        placeholder: $t('common.inputPhTxt', [$t('system.organization.userCount')]),
        required: true
      },
      {
        prop: 'type',
        label: $t('system.organization.tenantType'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('system.organization.tenantType')]),
        options: tenantTypeOptions,
        required: true
      },
      {
        prop: 'contact',
        label: $t('system.organization.contact'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('system.organization.contact')]),
        required: true
      },
      contactPhoneItem.value,
      {
        prop: 'contactEmail',
        label: $t('system.organization.email'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('system.organization.email')]),
        required: true,
        maxlength: 255
      },
      {
        prop: 'domain',
        label: $t('system.organization.domain'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('system.organization.domain')]),
        maxlength:50
      },
      {
        prop: 'activeTime',
        label: $t('system.organization.validTime'),
        type: 'daterange',
        placeholder: $t('common.selectPhTxt', [$t('system.organization.validTime')]),
        required: true,
        format: 'YYYY/MM/DD',
        'value-format': 'YYYY/MM/DD'
      },
      {
        prop: 'tenantLogo',
        label: $t('system.organization.tenantLogo'),
        render: () => {
          return (
            <ImageUpload
              ref={imageUploadRef}
              onUpdate:modelValue={(value) => {
                localFormData.value.tenantLogo = value;
              }}
              width="64px"
              height="32px"
              maxSize={5}
              showDelete={true}
            />
          )
        }
      }
    ];

    // 自定义用户数量验证函数
    const validateUserCount = (rule: any, value: any, callback: any) => {
      if (!value) {
        callback(new Error($t('common.inputPhTxt', [$t('system.organization.userCount')])))
        return
      }
      const numValue = Number(value)
      if (isNaN(numValue)) {
        callback(new Error($t('tenant.inputValidNumber')))
        return
      }
      if (!Number.isInteger(numValue)) {
        callback(new Error($t('tenant.inputInteger')))
        return
      }
      if (numValue < 1) {
        callback(new Error($t('tenant.userCountMin')))
        return
      }
      if (numValue > 99999) {
        callback(new Error($t('tenant.userCountMax')))
        return
      }
      callback()
    }

    // 表单验证规则
    const formRules = {
      userCount: [
        { validator: validateUserCount, trigger: 'blur' }
      ],
      contactPhone: [
        { required: true, message: $t('common.inputPhTxt', [$t('system.organization.phone')]), trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: $t('common.formatErrorTxt', [$t('common.phoneTxt')]), trigger: 'blur' }
      ],
      contactEmail: [
        { required: true, message: $t('common.inputPhTxt', [$t('system.organization.email')]), trigger: 'blur' },
        { type: 'email', message: $t('common.formatErrorTxt', [$t('common.emailTxt')]), trigger: 'blur' }
      ],
      domain: [
        { required: false, message: $t('common.inputPhTxt', [$t('system.organization.domain')]), trigger: 'blur' }
      ]
    };

    // 标题
    const title = computed(() => {
      return props.mode === 'add'
        ? $t('common.newTxt', [$t('tenant.tenant')])
        : $t('common.editTxt', [$t('tenant.tenant')]);
    });

    // 监听 modelValue 变化
    watch(() => props.modelValue, (val) => {
      visible.value = val;
    }, { immediate: true });

    //租户修改手机号
    const updatePhone = () => {
      showCodeBox({
        message: h('div', {}, [
          h('div', {}, [
            $t('system.organization.messages.updatePhoneTip', [props.formData.adminName, props.formData.adminPhone])
          ])
        ]),
        adminName: props.formData.adminName,
        adminPhone: props.formData.adminPhone,
        callback: (done: any) => {
          verifyPhoneCodeApi({
            phoneNumber: props.formData.adminPhone,
            verificationCode: authCode.value
          }).then((res) => {
            if (res === 'SUCCESS') {
              done();
              contactPhoneItem.value.disabled = false;
              contactPhoneItem.value.clearable = true;
              contactPhoneItem.value.slots = {};
            }
          })

        }
      })
    }


    watch(() => props.formData, (data) => {
      getMenuList(data.tenantId);
      if (data.id) {
        const { activeTime, ...rest } = data;
        localFormData.value = createMergedObject(initFormData(), rest);
        localFormData.value.name = rest.tenantName
        localFormData.value.id = data.id;
        localFormData.value.activeTime = activeTime?.split('-') || [];
        contactPhoneItem.value.clearable = false;
        contactPhoneItem.value.disabled = true;
        contactPhoneItem.value.slots = {
          suffix: () => <Pencil class="cursor-pointer w-4 h-4" onClick={updatePhone} />
        };
        nextTick(() => {
          console.log('data.tenantLogo', data.tenantLogo);
          imageUploadRef.value?.initImageData(data.tenantLogo);
        })
        // contactPhoneItem.value.disabled = true;
      } else {
        localFormData.value = initFormData();
        contactPhoneItem.value.slots = {};
        contactPhoneItem.value.disabled = false;
      }
    }, { immediate: true });
    // 处理关闭
    const handleClose = () => {
      emit('update:modelValue', false);
      emit('cancel');
    };

    // 处理确认
    const handleConfirm = async () => {
      if (!formRef.value) return;
      console.log('localFormData.value', localFormData.value);
      try {
        loading.value = true;
        // 表单验证
        const valid = await new Promise((resolve) => {
          formRef.value.validate((isValid: boolean) => {
            resolve(isValid);
          });
        });
        if (!valid) {
          return;
        }
        // 如果有图片需要上传，先上传图片
        try {
          const uploadResult = await imageUploadRef.value?.uploadToObs();
          if (uploadResult) {
            localFormData.value.tenantLogo = uploadResult.path;
          }
        } catch (error) {
          console.error('图片上传失败:', error);
          return;
        }

        // 发送确认事件
        // localFormData.value.menus 已经包含了完全选中和半选状态的节点
        emit('confirm', {
          ...localFormData.value,
          activeTime: localFormData.value.activeTime.join('-')
        });
      } catch (error) {
      } finally {
        loading.value = false;
      }
    };

    // 更新表单数据
    const handleFormUpdate = (data: any) => {
      localFormData.value = data;
    };

    const handleMenuChange = (checkedKeys: number[]) => {
      localFormData.value.menus = checkedKeys;
    };
    const handleMenuAllCheck = (checkedKeys: number[], isAllChecked: boolean) => {
      console.log('All check changed:', { checkedKeys, isAllChecked });
    };

    // 处理展开收起事件
    const handleMenuExpandCollapse = (isExpanded: boolean) => {
      console.log('Expand/Collapse changed:', isExpanded);
    };

    return () => (
      <BaseDrawer
        modelValue={visible.value}
        title={title.value}
        onUpdate:modelValue={(val: boolean) => emit('update:modelValue', val)}
        onClose={handleClose}
        onConfirm={handleConfirm}
        showFooter={true}
        confirmText={loading.value ? $t('tenant.submitting') : $t('common.submitTxt', [''])}
        cancelText={$t('common.cancelTxt')}
      >
        <div class="tenant-form-container">
          <div class="form-section">
            <div class="section-title">
              <h3>{$t('tenant.basicInfo')}</h3>
            </div>
            <div class="section-content">
              <base-form
                ref={formRef}
                columns={basicFormColumns}
                modelValue={localFormData.value}
                rules={formRules}
                label-position="right"
                label-width="90px"
                inline={true}
                onUpdate:modelValue={handleFormUpdate}
              />
            </div>
          </div>

          <div class="form-section">
            <div class="section-title">
              <h3>{$t('tenant.menuPermission')}</h3>
            </div>
            <div class="section-content tree-container">
              <MenuPermissionTree
                ref={menuTreeRef}
                data={menuList.value}
                tree-attrs={{
                  accordion: false,
                  highlightCurrent: true,
                  autoExpandParent: true,
                  emptyText: $t('tenant.noMenuData')
                }}
                checkbox-attrs={{
                  size: 'default',
                  border: false
                }}
                v-model={localFormData.value.menus}
                onUpdate:modelValue={handleMenuChange}
                onAllCheck={handleMenuAllCheck}
                onExpandCollapse={handleMenuExpandCollapse}
              />
            </div>
          </div>
        </div>
      </BaseDrawer>
    );
  },
});
</script>

<style lang="scss" scoped>
.tenant-form-container {
  .form-section {
    .section-title {
      @apply mb-4;

      h3 {
        margin: 0;
        font-size: 14px;
        font-weight: 500;
        color: #191919;
      }
    }

    .section-content {
      .basic-form {
        :deep(.base-form-item) {
          margin-bottom: 20px;

          .el-form-item__content {
            width: 100%;
          }
        }
      }

      .menu-permission-placeholder {
        padding: 40px 0;
        text-align: center;
      }
    }

    .tree-container {
      height: calc(100vh - 430px);
      overflow-y: auto;
    }
  }
}
</style>
